<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\wh\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\wh\model\Supplier as SupplierModel;
use app\wh\model\StockType as StockTypeModel;
use think\Db;

/**
 * 供应商控制器
 * @package app\admin\controller
 */
class Supplier extends Admin
{

    /**
     * 首页
     * @return mixed
     * @throws \Exception
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map2 = '1=1';
        foreach ($map as $mk=>$mv){
            if($mv[1] == 'find_in_set'){
                $map2 .= " and find_in_set('{$mv[2]}',{$mv[0]}) ";
                unset($map[$mk]);
            }
        }
        $map = array_merge($map);
        // 数据列表
        $data_list = Db::name('wh_supplier')
            ->where($map)
            ->where($map2)
            ->order('id desc')
            ->paginate()
            ->each(function ($v){

                $v['type_name'] = Db::name('wh_stock_type')->where([['id','in',$v['type_pid']]])->column('title');
                $v['type_name'] = implode(',',$v['type_name']);

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('供应商列表') // 页面标题
            ->setTableName('wh_supplier') // 设置表名
            //->hideCheckbox()
            ->setSearchArea([
                ['select:2', 'type_pid', '类型', 'find_in_set','',StockTypeModel::getGroup()],
                ['text:2', 'title', '供应商', 'like'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['type_name', '类型'],
                ['title_abb', '简称'],
                ['title', '供应商'],
                ['status', '状态', 'switch'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('add',['title' => '新增','href' => url('add'),'icon'=>'','class'=>'btn btn-primary'],['area' => ['780px', '65%'], 'title' => ['新增', 'font-size:24px;text-align: center;']])
            ->addTopButton('enable') // 添加顶部按钮
            ->addTopButton('disable') // 添加顶部按钮
            ->addRightButton('edit',['title' => '修改','href' => url('add',['id' => '__id__']),'icon'=>''],['area' => ['780px', '65%'], 'title' => ['修改', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 180,
                'status'  => 60,
            ])
            ->fetch(); // 渲染模板
    }

    /**
     * 新增
     * @param int $pid 所属父id
     * @return mixed
     * @throws \Exception
     */
    public function add($pid = 0)
    {

        $id = input('param.id');
        // 获取数据
        $info = Db::name('wh_supplier')->where(['id'=>$id])->find();

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');

            // 验证失败 输出错误信息
            if(empty($data['type_pid'])) $this->error('请选择类型');
            if(empty($data['title_abb'])) $this->error('简称不能为空');
            if(empty($data['title'])) $this->error('供应商不能为空');
            if(count($data['title_abb']) > 6) $this->error('简称不能超过6位');

            $data['type_pid'] = implode(',',$data['type_pid']);
            if($id){
                $data['id'] = $id;
                $re = SupplierModel::update($data);
            }
            else $re = SupplierModel::create($data);

            if ($re)$this->success('操作成功','','_parent_reload');
            else $this->error('操作失败');
        }

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增')
            ->addFormItems([
                ['select:12||||must', 'type_pid', '类型','',StockTypeModel::getGroup(),'', 'multiple'],
                ['text:12||||must', 'title_abb', '简称'],
                ['text:12||||must', 'title', '供应商'],
                ['text:12', 'sort', '排序', '', 100],
            ])
            ->setFormData($info)
            //->layout(['title'=>12,'sort'=>12,])
            ->fetch();
    }

    /**
     * 删除
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }

    /**
     * 启用
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids = (array)$ids;

        foreach ($ids as $id) {

            switch ($type) {
                case 'enable':
                    if (false === SupplierModel::where('id', $id)->setField('status', 1)) {
                        $this->error('启用失败，供应商ID：'.$id);
                    }
                    break;
                case 'disable':
                    if (false === SupplierModel::where('id', $id)->setField('status', 0)) {
                        $this->error('禁用失败，供应商ID：'.$id);
                    }
                    break;
                case 'delete':

                    if (false === SupplierModel::where('id', 'in', $id)->delete()) {
                        $this->error('删除失败，供应商ID：'.$id);
                    }
                    break;
                default:
                    $this->error('非法操作');
            }

            action_log('role_'.$type, 'wh', $id, UID);
        }

        $this->success('操作成功');
    }


}
